//
//  AppDelegate.m
//  DaJiang
//
//  Created by sally on 16/9/23.
//  Copyright © 2016年 jiniu. All rights reserved.
//

#import "AppDelegate.h"
#import "ChatManager.h"
#import "DatabaseSetting.h"
#import "TabOneViewController.h"
#import "XGPush.h"
#import <AFNetworkActivityLogger.h>
#import <IQKeyboardManager.h>
#import <UMSocialCore/UMSocialCore.h>
#import "WXApi.h"
#import "WXApiTool.h"
#import <AlipaySDK/AlipaySDK.h>

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  //配置网络访问日志
  [self setAFNetworkLog];
  //设置键盘属性
  [self setKeyboardManager];
  //设置环信
  [self setEaseMob:launchOptions application:application];
  //初始化地区缓存
  [self initLocUD];
  //设置信鸽
  [self setXGPush:launchOptions];
  //设置微信支付
  [WXApi registerApp:WXAppKey withDescription:@"demo 2.0"];
  

  //设置友盟分享
  [self setUMSocial];

  return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
}

#pragma mark APP进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application {
  [[EaseMob sharedInstance] applicationDidEnterBackground:application];
}

#pragma mark APP将要从后台返回
- (void)applicationWillEnterForeground:(UIApplication *)application {
  [[EaseMob sharedInstance] applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
  //设置APNS全局属性
  [ChatManager setNotificationOption];
  //进入app就清空通知栏
  [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

#pragma mark 将得到的deviceToken传给SDK
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  [[EaseMob sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];

  //注册设备
  [XGPush registerDevice:deviceToken];

  //缓存设备
  NSString *deviceTokenStr = [XGPush getDeviceToken:deviceToken];
  [[NSUserDefaults standardUserDefaults] setObject:deviceTokenStr forKey:UD_LAST_DEVICE_TOKEN];
}

#pragma mark 注册deviceToken失败
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  [[EaseMob sharedInstance] application:application didFailToRegisterForRemoteNotificationsWithError:error];
  NSLog(@"error -- %@", error);
}

#pragma mark 申请处理时间
- (void)applicationWillTerminate:(UIApplication *)application {
  [[EaseMob sharedInstance] applicationWillTerminate:application];
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
  return [self openURL:url];
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options{
  return [self openURL:url];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
  return [self openURL:url];
}

#pragma mark - UITabBarControllerDelegate,tab切换
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController {
  UINavigationController *nav = (UINavigationController *) viewController;
  UIViewController *rootVC = [nav.viewControllers objectAtIndex:0];
  if ([rootVC isKindOfClass:[TabOneViewController class]]) {
    TabOneViewController *vc = (TabOneViewController *) rootVC;
    vc.isFromTab = YES;
  }
  return YES;
}

#pragma mark - 私有方法
#pragma mark 配置网络访问日志
- (void)setAFNetworkLog {
  if (DEBUG) {
    // 开启AFNetworking调试日志
    [[AFNetworkActivityLogger sharedLogger] startLogging];
    if (AF_LOG_LEVEL == 1) {
      [[AFNetworkActivityLogger sharedLogger] setLevel:AFLoggerLevelDebug];
    } else if (AF_LOG_LEVEL == 0) {
      [[AFNetworkActivityLogger sharedLogger] setLevel:AFLoggerLevelOff];
    }
  }
}

#pragma mark 设置键盘属性
- (void)setKeyboardManager {
  //加载键盘遮挡优化
  [IQKeyboardManager load];
  //点击背景是否收起键盘
  [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
  //是否显示键盘上的工具条
  [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}

#pragma mark 设置环信
- (void)setEaseMob:(NSDictionary *)launchOptions application:(UIApplication *)application {
  // 创建数据库
  [[DatabaseSetting shareInstance] setShareDatabaseWithUserID:@"DaJiang"];

#warning 初始化环信SDK，详细内容在AppDelegate+EaseMob.m 文件中
#warning SDK注册 APNS文件的名字, 需要与后台上传证书时的名字一一对应
  NSString *apnsCertName = nil;
#if DEBUG
  apnsCertName = EaseMobDevCert;
#else
  apnsCertName = EaseMobProCert;
#endif

  //注册环信
  [[EaseMob sharedInstance] registerSDKWithAppKey:EaseMobAppKey apnsCertName:apnsCertName];
  [[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
}

#pragma mark 初始化地区缓存
- (void)initLocUD {
  //如果未设定位置，则初始化为“北京”
  NSString *locName = [[NSUserDefaults standardUserDefaults] objectForKey:UD_LAST_SELECT_LOC];
  if (locName.length < 1) {
    [[NSUserDefaults standardUserDefaults] setObject:@"北京" forKey:UD_LAST_SELECT_LOC];
  }
}

#pragma mark 设置信鸽
- (void)setXGPush:(NSDictionary *)launchOptions {
  [XGPush startApp:XGPushAppId appKey:XGPushAppKey];
  [XGPush handleLaunching:launchOptions];

  float sysVer = [[[UIDevice currentDevice] systemVersion] floatValue];
  if (sysVer < 8) {
    [self registerPush];
  } else {
    [self registerPushForIOS8];
  }
}

- (void)registerPushForIOS8 {
  //Types
  UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;

  //Actions
  UIMutableUserNotificationAction *acceptAction = [[UIMutableUserNotificationAction alloc] init];

  acceptAction.identifier = @"ACCEPT_IDENTIFIER";
  acceptAction.title = @"Accept";

  acceptAction.activationMode = UIUserNotificationActivationModeForeground;
  acceptAction.destructive = NO;
  acceptAction.authenticationRequired = NO;

  //Categories
  UIMutableUserNotificationCategory *inviteCategory = [[UIMutableUserNotificationCategory alloc] init];

  inviteCategory.identifier = @"INVITE_CATEGORY";

  [inviteCategory setActions:@[ acceptAction ] forContext:UIUserNotificationActionContextDefault];

  [inviteCategory setActions:@[ acceptAction ] forContext:UIUserNotificationActionContextMinimal];

  NSSet *categories = [NSSet setWithObjects:inviteCategory, nil];

  UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:categories];

  [[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];

  [[UIApplication sharedApplication] registerForRemoteNotifications];
}

- (void)registerPush {
  [[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound)];
}

#pragma mark 设置友盟分享
- (void)setUMSocial {
  //打开日志
  [[UMSocialManager defaultManager] openLog:YES];
  //设置友盟appkey
  [[UMSocialManager defaultManager] setUmSocialAppkey:UmSocialAppkey];
  
  //各平台的详细配置
  //设置微信的appId和appKey
  [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:WXAppKey appSecret:WXAppSecret redirectURL:UmRedirectURL];
  
  //设置分享到QQ互联的appId和appKey
  [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:QQAppKey appSecret:nil redirectURL:UmRedirectURL];
  
  //设置新浪的appId和appKey
  [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:SinaAppKey  appSecret:SinaAppSecret redirectURL:UmSinaRedirectURL];

  // 如果不想显示平台下的某些类型，可用以下接口设置
  [[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite),@(UMSocialPlatformType_Qzone),@(UMSocialPlatformType_TencentWb),@(UMSocialPlatformType_AlipaySession),@(UMSocialPlatformType_YixinSession),@(UMSocialPlatformType_YixinTimeLine),@(UMSocialPlatformType_YixinFavorite),@(UMSocialPlatformType_LaiWangSession),@(UMSocialPlatformType_LaiWangTimeLine),@(UMSocialPlatformType_Sms),@(UMSocialPlatformType_Email),@(UMSocialPlatformType_Renren),@(UMSocialPlatformType_Facebook),@(UMSocialPlatformType_Twitter),@(UMSocialPlatformType_Douban),@(UMSocialPlatformType_KakaoTalk),@(UMSocialPlatformType_Pinterest),@(UMSocialPlatformType_Line),@(UMSocialPlatformType_Linkedin),@(UMSocialPlatformType_Flickr),@(UMSocialPlatformType_Tumblr),@(UMSocialPlatformType_Instagram),@(UMSocialPlatformType_Whatsapp)]];
}

#pragma mark 设置第三方回调
-(BOOL)openURL:(NSURL *)url{
  if ([url.scheme isEqualToString:WXAppKey]) {
    if ([url.absoluteString rangeOfString:@"pay"].location != NSNotFound) {
      //微信支付
      return [WXApi handleOpenURL:url delegate:[WXApiTool sharedWXApiTool]];
    } else {
      //微信分享
      return [[UMSocialManager defaultManager] handleOpenURL:url];
    }
  } else {
    //支付宝
    if ([url.host isEqualToString:@"safepay"]) {
      //跳转支付宝钱包进行支付，处理支付结果
      [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
        NSLog(@"result = %@",resultDic);
        if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"]) {
          //通知订单页，支付宝支付成功
          [[NSNotificationCenter defaultCenter] postNotificationName:NoticePaySuccess object:self userInfo:resultDic];
        }
      }];
      return YES;
    }
    //分享
    return [[UMSocialManager defaultManager] handleOpenURL:url];
  }
}

@end
